package com.tm.controller;

import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tm.ResultEntity;
import com.tm.model.EcMemberInfo;
import com.tm.model.EcStoreManage;
import com.tm.model.EcTypeInfo;
import com.tm.model.SpLimitTimeShop;
import com.tm.model.SpOrder;
import com.tm.model.SpSkuInfo;
import com.tm.model.SpSpellGroup;
import com.tm.model.TtHeadlinesInfo;
import com.tm.pay.config.WechatConfig2;
import com.tm.service.CommonService;
import com.tm.service.EcMemberInfoService;
import com.tm.service.EcStoreManageService;
import com.tm.service.OrderService;
import com.tm.service.SpSkuInfoService;
import com.tm.util.CommonUtilsEx;
import com.tm.util.DateUtilsEx;
import com.tm.util.HttpRemoteCall;
import com.tm.util.JSONUtilsEx;
import com.tm.util.StringUtilsEx;
import com.tm.util.WeixinConfigUtil;

@Controller
public class IndexController {
	
	@Autowired
	private CommonService cService;
	
	@Autowired
	private EcMemberInfoService emiService;
	
	@Autowired
	private SpSkuInfoService ssiService;
	
	@Autowired
	private OrderService oService;
	
	@Autowired
	private EcStoreManageService esmService;
	
	/**
	 * 进入首页获取微信授权
	 * @param request
	 * @param response
	 */
	@RequestMapping("/")
	public void index_wechat_code(HttpServletRequest request, HttpServletResponse response){
		
		try {
			
			String state = StringUtilsEx.RandomString(32);
			request.getSession().setAttribute("wechat_order_state", state);
			
			String scope  = "snsapi_userinfo";//非静默授权
			String uri = "";
			if(StringUtils.isNotEmpty(request.getParameter("storeId"))){
				uri = URLEncoder.encode("http://app.tmaipay.com/main?storeId=" + request.getParameter("storeId"), "utf-8");
			}else{
				uri = URLEncoder.encode("http://app.tmaipay.com/main", "utf-8");
			}
			
			//获取access_token 
			String code_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + WechatConfig2.GZ_APPID 
					+ "&redirect_uri=" + uri + "&response_type=code&scope=" + scope + "&state="+state+"#wechat_redirect";
			
			response.sendRedirect(code_url);
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 微信自动登录获取用户信息（根据unionID判断是否已注册，未注册则走注册流程）
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/main")
	public String main(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
		
		String code = request.getParameter("code");
		
		//通过code获取access_token
		String access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WechatConfig2.GZ_APPID + "&secret=" + WechatConfig2.GZ_SECRET + "&code=" + code + "&grant_type=authorization_code";
		
		String access_token_str = HttpRemoteCall.buildRequest(access_token_url, new HashMap(), "utf-8", "", "", "GET");
		
		Map tokenmap = JSONUtilsEx.deserialize(access_token_str, Map.class);

		if(tokenmap.get("errcode") == null){
			String user_url = "https://api.weixin.qq.com/sns/userinfo?access_token=" + tokenmap.get("access_token") + "&openid=" + tokenmap.get("openid") + "&lang=zh_CN";
			
			String user_str = HttpRemoteCall.buildRequest(user_url, new HashMap(), "utf-8", "", "", "GET");
			
			Map usermap = JSONUtilsEx.deserialize(user_str, Map.class);
			
			System.out.println(usermap);

			String openid = String.valueOf(usermap.get("openid"));
			String unionid = String.valueOf(usermap.get("unionid"));
			String head = String.valueOf(usermap.get("headimgurl"));
			String nickname = String.valueOf(usermap.get("nickname"));
			
			request.getSession().setAttribute("openid", openid);
			request.getSession().setAttribute("unionid", unionid);
			request.getSession().setAttribute("head", head);
			
			//判断是否存在用户
			EcMemberInfo member = emiService.getMemberByUnionId(openid);
			
			if(member == null){
				//不存在该唯一标识用户信息，走注册流程
				member = new EcMemberInfo();
				if(StringUtils.isNotEmpty(request.getParameter("storeId"))){
					//获取店铺所属会员信息
					EcStoreManage store = esmService.getEcStoreManageByStoreId(Integer.parseInt(request.getParameter("storeId")));
					if(store != null){
						member.setParentMemberId(store.getMemberInfoId());
					}
				}
				member.setAddTime(DateUtilsEx.formatToString(new Date(), DateUtilsEx.DATE_FORMAT_SEC));
				member.setHead(head);
				member.setUnionId(openid);
				member.setMemberNick(nickname);
				
				emiService.addMember(member);
			}else{
				if(StringUtils.isNotEmpty(request.getParameter("storeId"))){
					//获取店铺所属会员信息
					EcStoreManage store = esmService.getEcStoreManageByStoreId(Integer.parseInt(request.getParameter("storeId")));
					if(store != null){
						member.setParentMemberId(store.getMemberInfoId());
					}
				}
				
				emiService.updateMember(member);
			}
			
			//自动登录
			request.getSession().setAttribute("memberId", member.getMemberInfoId());
			boolean isBind = false;
			if(StringUtils.isNotEmpty(member.getMobile())){
				isBind = true;
			}
			
			request.getSession().setAttribute("isBind", isBind);
		}
		
		return "main";
	}
	
	/**
	 * 跳转商城首页
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value = "/index")
	public String index(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception{
		
		if(StringUtils.isNotEmpty(request.getParameter("storeId"))){
			request.getSession().setAttribute("storeId", request.getParameter("storeId"));
		}
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		//自动登录
		/*request.getSession().setAttribute("memberId", 4);
		request.getSession().setAttribute("openid", "3136546");
		request.getSession().setAttribute("head", "../../img/avtar1.jpg");
		request.getSession().setAttribute("isBind", true);*/
		Integer memberId = (Integer) request.getSession().getAttribute("memberId");
		EcMemberInfo member = emiService.getmemberByMemberId(memberId);
		if(StringUtils.isNotEmpty(member.getMobile())){
			request.getSession().setAttribute("isBind", true);
		}
		
		/*****************************************加载微信jssdk 配置参数***************************************/
		Map<String, Object> rem = WeixinConfigUtil.getWxConfig(request);
		
		model.addAttribute("appId", rem.get("appId"));
		model.addAttribute("timestamp", rem.get("timestamp"));
		model.addAttribute("nonceStr", rem.get("nonceStr"));
		model.addAttribute("signature", rem.get("signature"));
		/*****************************************加载微信jssdk 配置参数***************************************/
		
		//获取首页banner
		List<Map<String, Object>> bannerList = cService.getAdvertisementByAdno("index-banner");
		model.addAttribute("bannerList", bannerList);
		
		//获取首页商品分类 页面暂定显示5个
		List<EcTypeInfo> typeList = cService.getEcTypeInfoForIndex();
		model.addAttribute("typeList", typeList);
		
		//获取活动商品（直降、团购）
		List<Map<String, Object>> sltsList = ssiService.getSpLimitTimeShopByPage(0, 1);
		
		List<Map<String, Object>> ssgList = ssiService.getSpSpellGroupByPage(0, 1);
		
		model.addAttribute("timeshop", sltsList.get(0));
		model.addAttribute("spellgroup", ssgList.get(0));
		
		//获取小编推荐模块商品
		List<Map<String, Object>> recommendSkuList = ssiService.getRecommendSkuListForIndex(0, 5);
		model.addAttribute("recommendSkuList", recommendSkuList);
		
		//获取商品热销模块商品
		List<Map<String, Object>> hotSkuList = ssiService.getRecommendSkuListForIndex(5, 10);
		model.addAttribute("hotSkuList", hotSkuList);
		
		return "index";
	}
	
	/**
	 * 跳转购物车页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/shopCart")
	public String shopCart(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws IOException {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		boolean flag = (boolean) request.getSession().getAttribute("isBind");
		
		if(!flag){
			return "member/bind/bind-mobile";
		}
		
		//获取购物车个人信息
		Integer memberId = (Integer) request.getSession().getAttribute("memberId");
		
		List<Map<String, Object>> list = ssiService.getShopCartByMemberId(memberId);
		
		model.addAttribute("list", list);
		model.addAttribute("cnt", list.size());
		
		return "shop-cart";
	}
	
	/**
	 * 跳转购物车结算页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/shopCartPay")
	public String shopCartPay(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		boolean flag = (boolean) request.getSession().getAttribute("isBind");
		
		if(!flag){
			return "member/bind/bind-mobile";
		}
		
		Integer memberId = (Integer) request.getSession().getAttribute("memberId");
		
		//获取会员基本信息
		EcMemberInfo member = emiService.getmemberByMemberId(memberId);
		model.addAttribute("member", member);
		
		String ids = request.getParameter("ids");
		
		//根据购物车详情明细id获取结算商品信息
		List<Map<String, Object>> list = ssiService.getShopCartPaySkuInfo(ids);
		for (Map<String, Object> sku : list) {
			if(Integer.parseInt(sku.get("stock_amount_rest").toString()) < Integer.parseInt(sku.get("sku_amount").toString())){
				model.addAttribute("msg", "商品" + sku.get("sku_name") + "库存不足！");
				return "error";
			}
		}
		model.addAttribute("list", list);
		
		String payMoney = request.getParameter("payMoney");
		model.addAttribute("payMoney", payMoney);
		model.addAttribute("ids", ids);
		
		//获取会员本次交易可使用积分
		Map<String, Object> score = oService.getScoreInfoByTransact(memberId, payMoney);
		model.addAttribute("score", score);
		
		Map<String, Object> address = null;
				
		String addrId = request.getParameter("addrId");
		if(StringUtils.isNotEmpty(addrId)){
			address = emiService.getAddressByAddrId(Integer.parseInt(addrId));
		}else{
			//获取会员默认地址
			address = emiService.getDefaultAddressByMemberId(memberId);
		}
		
		model.addAttribute("address", address);
		
		return "cart-pay";
	}
	
	/**
	 * 跳转直接购物结算页面
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/pay")
	public String pay(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		boolean flag = (boolean) request.getSession().getAttribute("isBind");
		
		if(!flag){
			return "member/bind/bind-mobile";
		}
		
		Integer memberId = (Integer) request.getSession().getAttribute("memberId");
		
		Integer skuId = Integer.parseInt(request.getParameter("skuId"));
		
		//获取商品基本信息
		SpSkuInfo sku = ssiService.getSpSkuInfoBySkuId(skuId);
		model.addAttribute("sku", sku);
		
		if(sku.getStockAmountRest() < Integer.parseInt(request.getParameter("skuAmount"))){
			model.addAttribute("msg", "库存不足！");
			return "error";
		}
		
		//获取商品团购信息
		SpSpellGroup group = ssiService.getSpSpellGroupBySkuId(skuId);
		model.addAttribute("group", group);
		
		//获取商品直降信息
		SpLimitTimeShop limit = ssiService.getSpLimitTimeShopBySkuId(skuId);
		model.addAttribute("limit", limit);
		
		//获取商品banner展示图
		List<Map<String, Object>> bannerList = ssiService.getSkuPicBySkuId(skuId);
		model.addAttribute("banner", bannerList.get(0).get("attach_path"));
		
		model.addAttribute("skuAmount", request.getParameter("skuAmount"));
		String money = request.getParameter("money");
		model.addAttribute("money", money);
		
		//获取会员本次交易可使用积分
		Map<String, Object> score = oService.getScoreInfoByTransact(memberId, money);
		model.addAttribute("score", score);
		
		Map<String, Object> address = null;
		String addrId = request.getParameter("addrId");
		if(StringUtils.isNotEmpty(addrId)){
			address = emiService.getAddressByAddrId(Integer.parseInt(addrId));
		}else{
			//获取会员默认地址
			address = emiService.getDefaultAddressByMemberId(memberId);
		}
		
		model.addAttribute("address", address);
		
		model.addAttribute("spellId", request.getParameter("spellId"));
		model.addAttribute("limitTimeId", request.getParameter("limitTimeId"));
		
		return "pay";
		
	}
	
	/**
	 * 生成微信支付参数
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/orderPay", method = RequestMethod.GET)
	public String orderPay(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		System.out.println("-------------------------------生成订单直接支付微信支付参数begin-----------------------------------------");
		try {
			String openid = (String) request.getSession().getAttribute("openid");
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");
			String orderId = request.getParameter("orderId");
			String ip = CommonUtilsEx.getIpAddr(request);
			ResultEntity re = null;
			
			re = oService.buildOrderPay(memberId, openid, orderId, ip);
			
			if("0".equals(re.getCode())){
				Map res = (Map) re.getData();
				
				model.addAttribute("appId", WechatConfig2.GZ_APPID);
				model.addAttribute("timeStamp", res.get("timeStamp"));
				model.addAttribute("nonceStr", res.get("nonceStr"));
				model.addAttribute("signType", res.get("signType"));
				model.addAttribute("package", res.get("package"));
				model.addAttribute("sign", res.get("sign"));
				model.addAttribute("orderId", res.get("orderId"));
			}else{
				model.addAttribute("errMsg", re.getText());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------------------------------生成订单直接支付微信支付参数end-----------------------------------------");

		return "WXJsPay";
		
	}
	
	/**
	 * 生成微信支付参数
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/WXJsPay", method = RequestMethod.GET)
	public String WXJsPay(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		System.out.println("-------------------------------生成微信支付参数begin-----------------------------------------");
		try {
			String openid = (String) request.getSession().getAttribute("openid");
			Integer memberId = (Integer) request.getSession().getAttribute("memberId");
			Integer storeId = Integer.parseInt(request.getParameter("storeId"));
			Float payMoney = Float.parseFloat(request.getParameter("payMoney"));
			Integer addrId = Integer.parseInt(request.getParameter("addrId"));
			String orderPoint = request.getParameter("orderPoint");//抵扣积分
			String ip = CommonUtilsEx.getIpAddr(request);
			if(ip.indexOf(",") > -1){
				//此时获取的IP为多个ip，取第一个ip
				String[] ips = ip.split(",");
				if(ips.length > 0){
					ip = ips[0];
				}
			}
			String ids = request.getParameter("ids");
			String skuId = request.getParameter("skuId");
			String skuAmount = request.getParameter("skuAmount");
			String skuPrice = request.getParameter("skuPrice");
			String tpn = request.getParameter("tpn");
			String spellId = request.getParameter("spellId");
			String limitTimeId = request.getParameter("limitTimeId");
			ResultEntity re = null;
			
			List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
			if(StringUtils.isNotEmpty(ids)){
				list = ssiService.getShopCartPaySkuInfo(ids);
				for (Map<String, Object> map : list) {
					map.put("sku_fee", new BigDecimal(map.get("sku_fee").toString()));
				}
			}
			
			re = oService.buildOrder(memberId, payMoney, payMoney, ip, openid, null, addrId, list, storeId, skuId, skuAmount, skuPrice, tpn, spellId, limitTimeId, orderPoint);
			
			if("0".equals(re.getCode())){
				Map res = (Map) re.getData();
				
				model.addAttribute("appId", WechatConfig2.GZ_APPID);
				model.addAttribute("timeStamp", res.get("timeStamp"));
				model.addAttribute("nonceStr", res.get("nonceStr"));
				model.addAttribute("signType", res.get("signType"));
				model.addAttribute("package", res.get("package"));
				model.addAttribute("sign", res.get("sign"));
				model.addAttribute("orderId", res.get("orderId"));
			}else{
				model.addAttribute("errMsg", re.getText());
				model.addAttribute("orderId", re.getData());
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------------------------------生成微信支付参数end-----------------------------------------");

		return "WXJsPay";
		
	}
	
	/**
	 * 跳转至支付成功页面
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/paySuccess", method = RequestMethod.GET)
	public String paySuccess(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		
		if(request.getSession().getAttribute("memberId") == null){
			index_wechat_code(request, response);
		}
		
		System.out.println("-------------------------------跳转至支付成功页面begin-----------------------------------------");
		try {

			String orderId = request.getParameter("orderId");
			
			//获取订单信息
			SpOrder order = oService.getOrderByOrderId(orderId);
			
			//获取收货地址信息
			Map<String, Object> address = emiService.getAddressByAddrId(order.getDeliveryAddrId());
			
			model.addAttribute("address", address);
			model.addAttribute("orderId", orderId);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------------------------------跳转至支付成功页面end-----------------------------------------");

		return "pay-success";
		
	}
	
	
	/**
	 * 跳转至资讯页面
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/infoList", method = RequestMethod.GET)
	public String infoList(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		
		System.out.println("-------------------------------跳转至资讯页面begin-----------------------------------------");
		try {
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------------------------------跳转至资讯页面end-----------------------------------------");

		return "info/list";
		
	}
	
	/**
	 * 跳转至资讯详情页面
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/infoDetail", method = RequestMethod.GET)
	public String infoDetail(ModelMap model, HttpServletRequest request, HttpServletResponse response) {
		
		System.out.println("-------------------------------跳转至资讯详情页面begin-----------------------------------------");
		try {
			
			Integer infoId = Integer.parseInt(request.getParameter("infoId"));
			
			TtHeadlinesInfo info = cService.getTtHeadlinesById(infoId);
			
			model.addAttribute("info", info);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("-------------------------------跳转至资讯详情页面end-----------------------------------------");

		return "info/detail";
		
	}
	
}
